package com.http.servletrequestlistener;

import jakarta.servlet.ServletRequestEvent;
import jakarta.servlet.ServletRequestListener;
import jakarta.servlet.annotation.WebListener;
import jakarta.servlet.http.HttpServletRequest;

import java.util.Date;

@WebListener
public class VisitorCounterListener implements ServletRequestListener {

    // 使用 ThreadLocal 来存储每个请求的开始时间
    private static final ThreadLocal<Long> startTime = new ThreadLocal<>();

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();

        // 记录开始时间
        startTime.set(System.currentTimeMillis());

        // 记录请求详细信息
        String clientIP = request.getRemoteAddr();
        String method = request.getMethod();
        String uri = request.getRequestURI();
        String queryString = request.getQueryString();
        String userAgent = request.getHeader("User-Agent");

        // 构建日志消息
        StringBuilder logMessage = new StringBuilder();
        logMessage.append("Request Started: ").append(new Date()).append("\n");
        logMessage.append("Client IP: ").append(clientIP).append("\n");
        logMessage.append("Method: ").append(method).append("\n");
        logMessage.append("URI: ").append(uri);
        if (queryString != null) {
            logMessage.append("?").append(queryString);
        }
        logMessage.append("\n");
        logMessage.append("User-Agent: ").append(userAgent).append("\n");

        System.out.println(logMessage.toString());
    }

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();

        // 计算并记录请求处理时间
        long endTime = System.currentTimeMillis();
        long processingTime = endTime - startTime.get();

        // 构建日志消息
        String logMessage = "Request Ended: " + new Date() +
                "\nProcessing Time: " + processingTime + "ms";

        // 使用日志框架记录
        System.out.println(logMessage); // 临时使用 System.out

        // 清理 ThreadLocal 变量
        startTime.remove();
    }
}
